package basic.practice;

import org.apache.activemq.ActiveMQConnectionFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;

import javax.jms.*;

/**
 * 
 * @author 42276
 * @author 任雪燕
 * @author 24372
 * @author 15869
 * @author admin
 * @author 张冰锋
 * @author 清风依旧
 * A producer of message-oriented middleware
 */
/**
 * 
 * @author 42276 The creation class for the message This class is set to create
 *         message
 */
public class Producer {
	// 定义ActivMQ的连接地址
	private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";// http://0.0.0.0:8161/ tcp://127.0.0.1:61616
	// 定义发送消息的队列名称
	private static final String QUEUE_NAME = "MessageFromPlaidShirt";

	public void MessageSend() throws JMSException, SQLException {
		// 创建连接工厂
		ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
		// 创建连接
		Connection connection = activeMQConnectionFactory.createConnection();
		// 打开连接
		connection.start();
		// 创建会话
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 创建队列目标
		Destination destination = session.createQueue(QUEUE_NAME);
		// 创建一个生产者
		javax.jms.MessageProducer producer = session.createProducer(destination);
		// 创建模拟100个消息

		String path = "D://Java//workspaces//plaid-shirt//basic-practice//src//main//resources//student_info.txt";// D:\Java\workspaces\plaid-shirt\basic-practice\src\main\resources
		File file = new File(path);
		BufferedReader reader = null;
		String tempString = null;

		try {

			reader = new BufferedReader(new FileReader(file));

			while ((tempString = reader.readLine()) != null) {

				TextMessage message = session.createTextMessage(tempString);
				// 发送消息
				producer.send(message);
				// 在本地打印消息
				System.out.println("Message Sending:" + message.getText());

			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// 关闭连接
		connection.close();
	}
}
